<template>
	<view style="background-color: #FFFFFF;min-height:100vh">
		<cu-custom>
		</cu-custom>
		<view style="position: relative;">
			<view style="position: absolute; right: 40px;top: 40px;" @tap="tapCurrentVersion()">
				<text class="cuIcon-info text-grey" style="font-size:36rpx;"></text>
			</view>
			<view class="ztnCustom-companyInfo">
				<image :src="companyIconUrl" class="png" mode="widthFix"></image>
				<text class="text-df">{{companyName}}</text>
			</view>
		</view>
		<view class="cu-list menu card-menu margin-top solid-bottom">
			<view class="cu-item">
				<view class="action">
					<input class="text-lg" id="userNameInput" @input="changeUserNameInput" :adjustPosition="true" maxlength="300"
						:cursor-spacing="10" :value="userName" :placeholder="$t('user')+$t('name')" />
				</view>
				<view class="action">
					<text class="cuIcon-close text-xl" style="color:#aaaaaa;" v-if="userName && userName.length != 0"
						@tap="cleanUserName"></text>
				</view>
			</view>
		</view>

		<view class="cu-list menu card-menu margin-top solid-bottom ">
			<view class="cu-item">
				<view class="action">
					<input id="passwordInput" :type="attention ? 'text':'password'" @input='changePasswordInput'
						:adjustPosition="false" :focus="focusPasswordInput" maxlength="300" :cursorSpacing="10"
						:value="password" :placeholder="$t('password')" class="text-lg" />
				</view>
				<view class="action">
					<view>
						<text :class="attention ? 'cuIcon-attentionfill':'cuIcon-attentionforbidfill'" class="text-xl"
							style="color:#aaaaaa;" @tap="changeAttention"></text>
						<!-- <text class="text-df text-black padding-left-sm" @tap="userForgetpsw">{{$t('forget')+$t('password')}}</text> -->
					</view>
				</view>
			</view>
		</view>

		<view class="padding-left-xs padding-right-xs">
			<view class="padding flex flex-direction">
				<button class="cu-btn round bg-green margin-tb-sm lg"
					:disabled="!userName || userName.length < 2 || password.length < 6" @tap="tapPswLogin">{{$t('login')}}</button>
				<view class="cu-bar bg-white">
					<view class="action" v-if="enableDemoAccount">
						<text class="text-df" @tap="tapDemoAccounUserLogin">{{$t('demo')+$t('user')}}</text>
					</view>
					<view class="action" v-if="enableRegister">
						<text class="text-df" @tap="userRegister">{{$t('register')}}</text>
					</view>
				</view>
			</view>
		</view>

		<view class="cu-bar bg-white solid-bottom" v-if="userList.length > 0">
			<view class="action">
				<text class="cuIcon-title text-orange "></text>{{$t('my') + $t('user')}}
			</view>
		</view>
		<view class="cu-list menu-avatar">
			<view class="cu-item cur" v-for="(item,index) in userList" :key="index" @tap="userClick(item)">
				<view class="cu-avatar radius lg" :style="{'background-image':'url('+item.iconUrl+')'}">
				</view>
				<view class="content">
					<view>
						<view class="text-cut">
							<text class="margin-right-xs"
								:class="item.status === 1 ? 'cuIcon-unlock': 'cuIcon-lock'"></text>
							{{item.userName}}
						</view>
					</view>
					<view class="text-gray text-sm flex">
						<view class="text-cut">{{formatDate(item.lastLoginDate)}}</view>
					</view>
				</view>
				<view class="action" @tap.stop="deleteBindByOpenid(item)">
					<view class="text-grey text-xs">{{item.loginNum}}</view>
					<view class="text-gray cuIcon-close"></view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		showToast,
		showModal
	} from '@/util/toast.js'
	import md5 from 'js-md5';
	import * as iotUserApi from '@/api/iot/iotUserApi.js'
	import * as authUserApi from '@/api/auth/authUserApi.js'
	import * as iotTokenApi from '@/api/iot/iotTokenApi.js'
	import * as authTokenApi from '@/api/auth/authTokenApi.js'
	import myConfig from '@/myConfig.js'
	import * as storage from '@/util/storage.js'
	import {
		formatDate
	} from '@/util/formatTime.js'
	export default {
		data() {
			return {
				openid: '',
				companyName: storage.getShortCompanyName(),
				companyIconUrl: storage.getCompanyIconUrl(),
				iconUrl: storage.getUserIconUrl(),
				userName: '',
				password: '',
				focusPasswordInput: false,
				attention: false,
				enableRegister: storage.getEnableRegister(),
				enableDemoAccount: storage.getEnableDemoAccount(),
				userList: [],
				userId: null,
				companyId: storage.getCompanyId(),
				lat: null,
				lng: null,
				country: null,
				province: null,
				city: null,
			}
		},
		computed: {
			themeConfig() {
				return this.$store.state.themeConfig
			}
		},
		onLoad() {
			this.init()
		},
		methods: {
			formatDate(time) {
				return formatDate(time)
			},
			tapCurrentVersion() {
				showModal(this.$t('version'), myConfig.app.version, false, this.$t('confirm'), this.$t('cancel'), (
					res) => {
					return
				})
			},
			listThirdPartyUserByOpenid() {
				iotUserApi.listThirdPartyUserByOpenid({
					openid: this.openid,
					type: this.loginType
				}).then(res => {
					const {
						data
					} = res
					this.userList = data
				})
			},
			deleteBindByOpenid(item) {
				iotUserApi.deleteBindByOpenid(item).then(() => {
					this.listThirdPartyUserByOpenid()
				})
			},
			init() {
				this.getUserLocation()
				this.getOpenId()
			},
			userClick(item) {
				this.userId = item.userId
				this.userName = null
				this.getToken()
			},
			getUserLocation() {
				const that = this
				uni.getLocation({
					type: 'gcj02',
					success: function(res) {
						that.lat = res.latitude
						that.lng = res.longitude
					},
					fail: function(error) {}
				});
			},
			getWxAppUserInfo() {
				uni.getUserProfile({
					// lang: 'zh_CN',
					desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
					success: (e) => {
						if (e.userInfo) {
							const {
								avatarUrl,
								nickName,
								language,
								country,
								province,
								city
							} = e.userInfo
							if (language.indexOf('zh') >= 0) {
								this.language = 'zh'
							} else if (language.indexOf('en') >= 0) {
								this.language = 'en'
							} else {
								this.language = 'zh'
							}
							this.country = country
							this.province = province
							this.city = city
							this.iconUrl = avatarUrl
							this.nickName = nickName
						}
						this.bindWxAppUser()
					},
					fail: (err) => {
						console.log(err)
						this.bindWxAppUser()
					}
				})
			},
			bindWxAppUser() {
				iotUserApi.bindUser({
					companyId: this.companyId,
					openid: this.openid,
					isDemoAccount: this.isDemoAccount,
					nickName: this.nickName,
					iconUrl: this.iconUrl,
					language: this.language,
					country: this.country,
					province: this.province,
					city: this.city,
					type: this.loginType,
					userName: this.userName,
					password: md5(this.password)
				}).then((res) => {
					this.getToken()
				})
			},
			getOpenId() {
				//#ifdef MP-WEIXIN
				this.loginType = 'wxApp'
				wx.login({
					success: (res) => {
						iotUserApi.getWxAppSession({
							code: res.code,
							companyId: this.companyId
						}).then((sessionRes) => {
							this.openCode = res.code
							this.openid = sessionRes.data.openid
							this.listThirdPartyUserByOpenid()
						})
					},
					fail: (err) => {
						console.error(err)
						showToast(this.$t('user') + this.$t('info') + this.$t('failure'), 'none', 2000, false)
					}
				});
				//#endif
				//#ifndef MP-WEIXIN
				const url = window.location.href;
				const params = url.split('?')[1];
				if (params) {
					const urlSearchParams = new URLSearchParams(params);
					if (urlSearchParams && urlSearchParams.get('from') == 'singlemessage') {
						this.openid = urlSearchParams.get('openid');
						if (this.openid) {
							this.loginType = 'gzh'
						} else {
							this.loginType = 'uni'
						}
						this.listThirdPartyUserByOpenid()
					}
				}
				//#endif
			},
			changeUserNameInput(e) {
				this.userName = e.detail.value.replace(/\s/g, '')
			},
			cleanUserName() {
				this.userName = ''
			},
			changePasswordInput(e) {
				this.password = e.detail.value.replace(/\s/g, '')
			},
			changeAttention() {
				this.attention = !this.attention
				this.focusPasswordInput = true
			},
			userForgetpsw() {
				showToast(this.$t('unSupport'), 'none', 1000, false) //暂没开通
			},
			getToken() {
				iotTokenApi.userLogin({
					isDemoAccount: this.isDemoAccount,

					userName: this.userName,
					password: md5(this.password),

					openid: this.openid,
					openCode: this.openCode,

					companyId: this.companyId,
					userId: this.userId,
					iconUrl: this.iconUrl,
					loginType: this.loginType,
					lat: this.lat,
					lng: this.lng
				}).then((res) => {
					const {
						data
					} = res
					if (data) {
						const {
							accessToken
						} = data
						storage.setNickName(this.nickName)
						storage.setOpenid(this.openid)
						storage.setUserIconUrl(this.iconUrl)
						storage.setToken(accessToken)
						this.getUser()
					} else {
						showToast(this.$t('not') + this.$t('bind') + this.$t('user'), 'none', 1000, false)
					}
				})
			},
			getUser() {
				authUserApi.getUser({}).then(res => {
					const {
						data
					} = res
					if (data) {
						const {
							userId,
							deptId,
							userName,
							language,
							lat,
							lng
						} = data
						storage.setUserId(userId)
						storage.setDeptId(deptId)
						storage.setUserName(userName)
						storage.setLanguage(language)
						storage.setLat(lat)
						storage.setLng(lng)
						uni.redirectTo({
							url: `/pages/nav/nav`
						})
					}
				})
			},
			tapLogin() {
				for (const user of this.userList) {
					if (user.userName === this.userName) {
						this.userClick(user)
						return
					}
				}
				//#ifdef MP-WEIXIN
				this.getWxAppUserInfo()
				//#endif
				//#ifdef H5
				if (this.openid) {
					iotUserApi.bindUser({
						companyId: this.companyId,
						userName: this.userName,
						password: md5(this.password),
						openid: this.openid,
						type: this.loginType
					}).then((res) => {
						this.getToken()
					})
				} else {
					this.getToken()
				}
				//#endif
				//#ifdef APP-PLUS
				this.getToken()
				//#endif
			},
			tapPswLogin() {
				this.isDemoAccount = false
				this.tapLogin()
			},
			tapDemoAccounUserLogin() {
				this.isDemoAccount = true
				this.tapLogin()
			},
			userRegister() {
				uni.redirectTo({
					url: `/pages/register/register`
				});
			},
		}
	}
</script>

<style scoped>
	.ztnCustom-companyInfo {
		padding-top: 40rpx;
		display: flex;
		justify-content: center;
		flex-direction: column;
		align-items: center;
	}

	.ztnCustom-companyInfo text {
		opacity: 0.8;
	}

	.ztnCustom-companyInfo image {
		width: 200rpx;
		height: 200rpx;
	}

	.ztnCustom-middle-line:before {
		content: '';
		display: block;
		height: 2rpx;
		width: 100%;
		background-color: #ddd;
		/*颜色需与主题大背景色一致*/
		position: relative;
		top: 18rpx;
		left: 0;

	}

	.ztnCustom-line-text {
		display: inline-block;
		background: #fff;
		padding: 0 20rpx 0 20rpx;
		position: relative;
	}

	.custom-button {
		position: relative;
		display: block;
		margin-left: auto;
		margin-right: auto;
		padding-left: 0px;
		padding-right: 0px;
		box-sizing: border-box;
		text-align: center;
		text-decoration: none;
		line-height: 1;
		border-radius: 5px;
		-webkit-tap-highlight-color: transparent;
		overflow: hidden;
		background-color: rgba(0, 0, 0, 0);
	}

	.custom-button::after {
		border: 0;
	}

	.custom-button-hover {
		background-color: #fff;
	}
</style>
